package application.common.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.net.URLDecoder;
import java.util.LinkedList;
import java.util.List;

public class FiltUtil {
	public static String getPath() {
		URL url = FiltUtil.class.getProtectionDomain().getCodeSource().getLocation();
		String filePath = null;
		try {
			filePath = URLDecoder.decode(url.getPath(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		filePath = filePath.substring(1, filePath.lastIndexOf("/") + 1);
		return filePath;
	}

	// 创建文件上传路径
	public static void mkdir(String path) {
		File fd = null;
		try {
			fd = new File(path);
			if (!fd.exists()) {
				fd.mkdirs();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			fd = null;
		}
	}

	/**
	 * 删除空目录
	 * 
	 * @param dir 将要删除的目录路径
	 */
	public static void doDeleteEmptyDir(String dir) {
		new File(dir).delete();
	}

	/**
	 * 递归删除目录下的所有文件及子目录下所有文件
	 * 
	 * @param dir 将要删除的文件目录
	 * @return boolean Returns "true" if all deletions were successful. If a
	 *         deletion fails, the method stops attempting to delete and returns
	 *         "false".
	 */
	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			//递归删除目录中的子目录下
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// 目录此时为空，可以删除
		return dir.delete();
	}

	public static boolean writeFile(String path, String content) {
		Writer writer = null;
		try {

			File file = new File(path);
			if (!file.exists()) {
				file.createNewFile();
			}
			writer = new FileWriter(file, false);
			writer.write(content);
			return true;
		} catch (IOException e) {
		} finally {
			try {
				writer.close();
			} catch (IOException e2) {
			}
		}
		return false;
	}
	
	public static List<File> getList(String path){
		List<File> files=new LinkedList<File>();
		File file = new File(path);
		if(file.exists() && file.list().length>0) {
			for(File f:file.listFiles()) {
		        String fileSuffix = f.getName().substring(f.getName().lastIndexOf(".") + 1);
		        if("png".equalsIgnoreCase(fileSuffix) || "jpg".equalsIgnoreCase(fileSuffix)) {
		        	files.add(f);
		        }
			}
		}
		return files;
	}

}
